<template>
  <div class="carryway-consumption-address">
    <div class="block">
      <div class="amount">
        <span class="number"
          >消耗产品数量：<span style="color:red">{{
            totalConsumptions
          }}</span></span
        >
        <span class="money"
          >总金额(元)：<span style="color:red">{{ totalAmounts }}</span></span
        >
      </div>
      <header>
        <h2 class="required">
          承运方式
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item>
            <el-radio-group v-model="carryway" @change="onChangeCarrayway">
              <el-radio
                v-for="item in rows_carryway"
                :key="item.enumKey"
                :label="item.enumKey"
              >
                {{ item.enumVal }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div v-if="showAddress" class="block blockSection">
      <header>
        <h2 class="required">
          收货地址
        </h2>
      </header>

      <section>
        <el-radio-group
          v-model="address"
          class="w100p address-group"
          @change="onChangeAddress"
        >
          <el-row
            v-for="item in rows_address"
            :key="item.id"
            class="address-line"
          >
            <el-col
              class="address-item"
              :class="{ highline: item.id === address }"
            >
              <el-radio-button :label="item.id" class="title">
                <div class="userName">
                  <div class="userNameLeft">
                    <div class="addressItemLeft">
                      <span>收货人：{{ item.userName }}</span>
                    </div>
                    <div class="addressItemCenter">
                      <span>联系电话：{{ item.userPhone }}</span>
                    </div>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="
                        item.province +
                          item.city +
                          item.area +
                          item.detailedAddress
                      "
                      placement="top"
                    >
                      <div class="addressItemRight">
                        <div class="addressItem">
                          <span
                            >地址：{{ item.province }} {{ item.city }}
                            {{ item.area }} {{ item.detailedAddress }}</span
                          >
                        </div>
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="buttonItem">
                    <el-button
                      v-if="item.id === address"
                      size="small"
                      class="editButton"
                      type="text text-primary"
                      style="margin-right:10px;color: #999999"
                      @click="openAddressAddDialog(item)"
                    >
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="编辑"
                        placement="top"
                      >
                        <m-iconfont
                          classify="m-pc-public"
                          icon="m-pc-public_bianj"
                          size="16"
                        />
                      </el-tooltip>
                    </el-button>
                    <el-button
                      v-if="item.id === address"
                      size="small"
                      class="deleteButton"
                      type="text text-primary"
                      style="color: #999999;"
                      @click="deleteAddress(item.id)"
                    >
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="top"
                      >
                        <m-iconfont
                          classify="m-pc-public"
                          icon="m-pc-public_shanc"
                          size="16"
                        />
                      </el-tooltip>
                    </el-button>
                  </div>
                </div>
              </el-radio-button>
            </el-col>
          </el-row>
          <div style="display: flex;">
            <el-link
              type="primary"
              :underline="false"
              @click="openAddressAddDialog()"
            >
              <m-iconfont
                classify="m-pc-public"
                icon="m-pc-public_tianj"
                size="14"
              /><span>新增收货地址</span>
            </el-link>
            <div v-if="showMoreAddress" class="more">
              <el-button
                v-if="toggleMoreAddress === false"
                type="text"
                @click="onClickMoreAddress"
              >
                更多地址
                <i class="el-icon-arrow-down" />
              </el-button>
              <el-button v-else type="text" @click="onClickLessAddress">
                收起
                <i class="el-icon-arrow-up" />
              </el-button>
            </div>
          </div>
        </el-radio-group>
      </section>
    </div>
  </div>
</template>

<script>
import {
  commonEnum,
  getOrderAddressByUserId,
  deleteOrderAddress
} from '@api/m_mall_web_v1.js';
import { AddressAddDialogService } from '~/modules/address/address-add.dialog.module';

export default {
  props: {
    carrywayId: {
      type: String,
      default: ''
    },
    addressId: {
      type: String,
      default: ''
    },
    totalAmount: {
      type: Number,
      default: 0
    },
    totalConsumption: {
      type: Number,
      default: 0
    },
    orderTypeId: {
      type: String,
      default: ''
    },
    payWayId: {
      type: String,
      default: ''
    },
    activeIndex: {
      type: Number,
      default: 0
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'wholesale'
    },
    allData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      order_type_ops: [],
      rows_carryway: [],
      rows_address_full: [],
      rows_address: [],
      rows_payway: [
        {
          key: '1',
          value: '在线支付（流程全自动化，迅速快捷下单，订单状态可跟踪）'
        },
        { key: '2', value: '线下支付（人工处理，此单使用积分、返利等）' }
      ],
      carryway: '',
      itemAddress: {},
      address: '',
      totalConsumptions: 0,
      totalAmounts: '',
      payway: '',
      ordertype: '',
      toggleMoreAddress: false,
      showMoreAddress: false,
      showAddress: true
    };
  },
  computed: {
    addressAddDialogService() {
      return new AddressAddDialogService(this.$axios);
    }
  },
  watch: {
    carrywayId: {
      handler(val) {
        this.carryway = val;
        if (this.carryway === '123') {
          this.showAddress = false;
        } else {
          this.showAddress = true;
        }
      },
      immediate: true
    },
    addressId: {
      handler(val) {
        this.address = val;
        const address = this.rows_address.find(item => item.id === val);
        this.$emit('change-address', address);
      },
      immediate: true
    },
    totalConsumption: {
      handler(val) {
        this.totalConsumptions = val;
      },
      immediate: true
    },
    totalAmount: {
      handler(val) {
        this.totalAmounts = val;
        this.totalAmounts = this.totalAmounts.toFixed(2);
      },
      immediate: true
    },
    orderTypeId: {
      handler(val) {
        this.ordertype = val;
      },
      immediate: true
    },
    payWayId: {
      handler(val) {
        this.payway = val;
      },
      immediate: true
    }
  },
  async created() {
    this.$axios({
      method: 'post',
      url: commonEnum,
      data: { indexCode: 'transportType' }
    }).then(res => {
      this.rows_carryway = res.data.payload;
      this.rows_carryway[0].enumVal = '自提';
    });
    await this.reloadAddress(this.changeAddressList);
  },
  methods: {
    onChangeOrderType(value) {
      this.$emit('update:orderTypeId', value);
    },
    onChangeCarrayway(value) {
      this.$emit('update:carrywayId', value);
    },
    onChangePayWay(value) {
      this.$emit('update:payWayId', value);
    },
    onChangeAddress(value) {
      this.$emit('update:addressId', value);
      const address = this.rows_address.find(item => item.id === value);
      this.$emit('change-address', address);
    },
    onClickMoreAddress() {
      this.rows_address = this.rows_address_full;
      this.toggleMoreAddress = true;
    },
    onClickLessAddress() {
      this.rows_address = this.rows_address_full.slice(0, 2);
      this.toggleMoreAddress = false;
    },
    // 删除地址
    deleteAddress(id) {
      this.$confirm('是否要删除此收货地址？', '删除收货地址', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            id
          };
          this.$axios.$post(deleteOrderAddress, params).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.toggleMoreAddress = false;
            this.reloadAddress();
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    openAddressAddDialog(item) {
      if (item) {
        if (item.id) {
          this.itemAddress = item;
          this.addressAddDialogService
            .create({
              title: '新增收货地址',
              data: this.itemAddress,
              query: {},
              confirmButtonClickHandler: (data = {}) => {
                // 刷新完后，默认选中刚新增的记录上
                this.toggleMoreAddress = false;
                if (data) {
                  this.reloadAddress();
                }
              }
            })
            .mount();
        }
      } else {
        this.addressAddDialogService
          .create({
            title: '新增收货地址',
            query: {},
            confirmButtonClickHandler: (data = {}) => {
              // 刷新完后，默认选中刚新增的记录上
              this.toggleMoreAddress = false;
              if (data) {
                this.reloadAddress();
              }
            }
          })
          .mount();
      }
    },
    changeAddressList() {
      if (this.rows_address_full.length > 0) {
        let index = this.rows_address_full.findIndex(
          item => item.id === this.address
        );
        // console.log(this.rows_address_full, 'index')
        index = index < 0 ? 0 : index;
        this.rows_address_full.splice(
          0,
          0,
          this.rows_address_full.splice(index, 1)[0]
        );
      }
    },
    reloadAddress() {
      this.$axios({
        method: 'post',
        url: getOrderAddressByUserId
      }).then(res => {
        if (!res.data.code) return;
        this.rows_address_full = res.data.payload || [];
        // 存在地址列表
        if (this.rows_address_full.length) {
          // 且非编辑模式，那么就默认选中第一个
          if (!this.isEdit) {
            const address = this.rows_address_full[0];
            this.$emit('change-address', address);
            this.address = address.id;
            this.$emit('update:addressId', this.address);
          } else {
            const address = this.rows_address_full.find(
              item => item.id === this.address
            );
            // this.address = address.id;
            this.$emit('update:addressId', this.address);
            this.$emit('change-address', address);
          }
        } else {
          const address = {};
          address.area = '';
          address.city = '';
          address.province = '';
          address.detailedAddress = '';
          address.userPhone = '';
          address.userName = '';
          address.id = '';
          this.address = address.id;
          this.$emit('update:addressId', this.address);
          this.$emit('change-address', address);
        }

        if (this.isEdit === false) {
          this.rows_address = this.rows_address_full.slice(0, 3);
        } else {
          this.rows_address = this.rows_address_full;
        }
        this.showMoreAddress =
          this.rows_address_full.length > this.rows_address.length;
      });
    }
  }
};
</script>

<style lang="less">
.carryway-consumption-address {
  background: #ffffff;
  padding-top: 20px;
  .block {
    padding: 0 20px 0 20px;
    margin: 0;
    .amount {
      // width: 100%;
      padding: 0.9% 0.9% 0.9% 1.4%;
      background: #f5f8ff;
      .number,
      .money {
        font-size: 16px;
        color: #4d84ff;
        line-height: 22px;
      }
      .number {
        margin-right: 60px;
      }
    }
    header {
      border: none;
      padding: 12px 16px 12px 0;
    }

    section {
      border: none;
      padding: 0 0 0 20px;
      .el-radio {
        margin-right: 80px;
      }
    }
  }
  // .blockSecond{
  //   padding: 0 20px 0 20px;
  // }
  .el-button.el-button--text,
  .el-link--inner {
    color: #4d84ff;
    // margin-top: 10px;
  }
  .el-radio.is-checked {
    .el-radio__inner {
      background: #4d84ff;
      border: 1px solid #4d84ff;
    }
    .el-radio__label {
      color: #4d84ff;
    }
  }
  .address-group {
    font-size: inherit;
    .address-item {
      width: 100%;
      .title.el-radio-button {
        position: relative;
        width: 100%;
        height: 50px;
        margin-bottom: 10px;
        .el-radio-button__inner {
          width: 100%;
          height: 50px;
          line-height: 50px;
          // .name {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          // }
        }
        .box {
          width: 0;
          height: 0;
          position: absolute;
          right: -60px;
          bottom: 0;
          color: blue;
          border-bottom: 24px solid red;
          border-left: 24px solid transparent;
        }
      }
      .el-radio-button:first-child:last-child .el-radio-button__inner {
        width: 100%;
        height: 50px;
        color: #333333;
        border: 1px solid #e6e6e6;
        border-radius: 3px;
        line-height: 30px;
        .userName {
          display: flex;
          justify-content: space-between;
          .userNameLeft {
            width: 90%;
            display: flex;
            .addressItemLeft {
              position: relative;
              width: 12%;
              margin-right: 5%;
              span {
                position: absolute;
                left: 0;
              }
            }
            .addressItemCenter {
              position: relative;
              width: 20%;
              margin-right: 5%;
              span {
                position: absolute;
                left: 0;
              }
            }
            .addressItemRight {
              width: 55%;
              .addressItem {
                width: 100%;
                position: relative;
                span {
                  width: 100%;
                  position: absolute;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  left: 0;
                }
              }
            }
          }
          .buttonItem {
            width: 10%;
            .editButton :hover {
              color: #4d84ff;
            }
            .deleteButton :hover {
              color: #4d84ff;
            }
          }
        }
      }
      .el-radio-button.is-active:first-child:last-child
        .el-radio-button__inner {
        width: 100%;
        height: 50px;
        background: #ffffff;
        border: 1px solid #ff0000;
        border-radius: 3px;
        color: #333333;
        line-height: 30px;
      }
    }
    .more {
      width: 120px;
      text-align: center;
    }
  }
  .highline {
    color: #2371c5;
    font-weight: bold;
  }
  .overflow-text {
    display: inline-block;
    width: 24%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: -2px;
  }
}
</style>
